# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : orderlines_start_view.py
# Time       ：2023/3/12 14:44
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    启动流程视图
    start process views
"""
import traceback
import uuid

from flask import request
from flask_restx import fields

from apis.orderlines import orderlines_ns
from public.api_utils.api_decorator import handle_api_error
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView
from public.logger import logger

start = {'process_instance_id': fields.String(description='流程ID')}
orderlines_start_marshal = MarshalModel('start', orderlines_ns)
response_mode = orderlines_start_marshal.detail_response(start, False)


class OrderLinesStartView(AbstractView):
    url = '/start'

    def __init__(self, *args, **kwargs):
        super(OrderLinesStartView, self).__init__(*args, **kwargs)
        self.form_data = request.json
        self.is_logger = True

    @handle_api_error()
    @orderlines_ns.expect(orderlines_start_marshal.detail_request(start))
    @orderlines_ns.marshal_with(response_mode)
    def post(self):
        """流程开始"""
        try:
            from tasks.orderlines_run import orderlines_run

            process_id = self.form_data.get('id') or self.form_data.get('process_id')
            process_instance_id = uuid.uuid4().hex
            orderlines_run.delay(process_id=process_id, process_instance_id=process_instance_id, run_type='trigger')
            response_data = {'process_instance_id': process_instance_id}
            return generate_response(message='process begin run!', data=response_data, model=response_mode)
        except Exception as e:
            logger.error(f'流程启动失败:{e}\n {traceback.format_exc()}')
            return generate_response(code=500, message='process start failure')
